class Icon < Asset

  attr_accessor :crop_x, :crop_y, :crop_w, :crop_h

  after_update  :reprocess_photo, :if => :cropping?

  has_attached_file :attachment,

    :styles => {
        #Product detail (not main photo)
        :small_thumb => {
          :geometry => Setting.get("photo_small_thumb_size"),
          :processors => [:cropper],
          :quality => 40,
          :format => 'JPG'
        },
     },

    :default_style => :small_thumb

    validates :attachment_file_name, :presence => true if lambda {|attr| attr.object.new_record?}
    validates_attachment_content_type :attachment, :content_type => ['image/jpeg', 'image/gif', 'image/x-png', 'image/png']
    validate :attachment_check

    def photo_geometry(style = :original)
      @geometry ||= {}
      @geometry[style] ||= Paperclip::Geometry.from_file(attachment.path(style))
    end

    def attachment_check
      unless attachment.errors.empty?
        errors.add(:base, "Při upravování fotky ('#{attachment_file_name}') došlo k chybě. Zkontrolujte ImageMagick, nebo zdrojový soubor.")
        false
      end
    end

    def cropping?
      !crop_w.blank? && !crop_h.blank?
    end

    private
    def reprocess_photo
      attachment.reprocess!
    end
end
